const app     = getApp()
const request = require('../../utils/request.js');
const config = require('../../utils/config.js');
const QQMapWX = require('../..//utils/qqmap-wx-jssdk.js'),
mapsdk = new QQMapWX({key: app.globalData.mapSdkKey});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    topBarHeight: 64,
    resultPop: false,
    is_success:false,
    jihuoPop: false,
    firstFocus: false,
    foucusPop:false,
    mima: '',
    showPrivacy:false,
    nowList:{  
        total: 0,
        current_page: 0,
        last_page: 1,
        data: []
      },
      region:[],
      multiArray: [],
      multiIndex: [0,0,0],
      chinaData: [],
    isTrue:false,
    privacyContractName:'新眼光健康管理小程序隐私保护指引》',
    contact_phone:'',
    userInfo:null,
    lng:'',
    lat: '',
    longitude:'',
    latitude:'',
    card_no:'',
    mini_logo:'',
    fail_msg:''
  },
  getCommon()
  {
      var that =this;
    request.requestLoading(
        "/api/common/init_config",
        {},
        'GET',
    ).then((res) => {
       console.log(res.data.contact_phone);
      that.setData({
        contact_phone:res.data.contact_phone,
        mini_logo:res.data.mini_logo?res.data.mini_logo:'/static/icon/icon_logo1.png'
      })
     
    }).catch((err) => {
      // console.error(err);
      
    });
  },
  gocards(){
    wx.navigateTo({
      url: '/pages/my_rights/index',
    })
  },
  gouserInfo(){
   wx.navigateTo({
     url: '/pages/edit_info/index',
   })
  },
  inputCard(e){
   this.setData({
       card_no:e.detail.value
   })
  },
  gorights(){
    if(this.checkLogin()){
        wx.navigateTo({
          url: '/pages/my_rights/index',
        })
    }
 },
 goappoint(){
     if(this.checkLogin()){
         wx.navigateTo({
           url: '/pages/my_appointment/index',
         })
     }
 },
  refuse(){
   this.setData({
       showPrivacy:false
   })
  },
getMine(){
    request.requestLoading(
        "/api/login/getMorders",
        {
         
        },
        'POST',
      ).then((res) => {
     that.setData({
        appoints:res.data.appoints,
        benefits:res.data.benefits,
     })
       
  
      }).catch((err) => {
        console.error(err);
      });
},

  sure_activate(){
  
   var that = this;

   if(this.data.mima.length!=9){
       request.toast('请填写卡密');
       return;
   }
   that.setData({
    foucusPop:false,
    firstFocus:false,
   })
   request.requestLoading(
       "/api/appoint/sure_activate",
       {
        card_key:that.data.mima
       },
       'POST',
     ).then((res) => {
         console.log(res)
        that.setData({
            mima:''
        })
        if(res.code){
            that.setData({
                is_success:true,
                resultPop:true,
              
                
            })
        }else{
          that.setData({
            fail_msg:res.data,
              is_success:false,
              resultPop:true,
           
          })
        }
        that.setData({
           
            resultPop:true
        })
      
 
     }).catch((err) => {
       console.error(err);
     });
  },
  openmap(e){
  var  index = e.currentTarget.dataset.index;
  var mdata =this.data.nowList.data[index];
  console.log(mdata)
  if(mdata){
      var address=mdata.province+mdata.city+mdata.area+mdata.address;

      wx.openLocation({

        latitude:Number(mdata.lat),
        
        longitude: Number(mdata.lng),
        
        name: mdata.hospital_name,
        
        address: address,
        
        scale: 18,
        
        success: function(res) {
        
        console.log(res)
        
        },
        
        fail: function(err) {
        
        console.log(err)
        
        }
        
        })
        
        
 
  }
  },
  bindMultiPickerChange: function (e) {
    this.setData({
      isTrue:true
    })
    console.log(e)
    var move = e.detail;
    var value = move.value;
    console.log(value)
    this.setData({
        multiIndex: [value[0], value[1], value[2]]

      })
    var array=[],that =this;
    array[0]=  that.data.multiArray[0][that.data.multiIndex[0]];
    array[1]=that.data.multiArray[1][that.data.multiIndex[1]];
    array[2]=that.data.multiArray[2][that.data.multiIndex[2]];
    app.globalData.defaultCity=array[0]+','+array[1]+','+array[2]
    var that =this;
    that.setData({
        'nowList.current_page': 0,
    });
    that.getCurrentHospital()
  },
  bindMultiPickerColumnChange: function (e) {
      console.log(e)
    var move = e.detail;
    var index = move.column;
    var value = move.value;
    console.log(111234)
    if (index == 0) {
      this.setData({
        multiIndex: [value, 0, 0]
      })
      this.getCity();
    }
    if (index == 1) {
      this.setData({
        "multiIndex[1]": value,
        "multiIndex[2]": 0,
      })
      this.getXian();
    }
   
    if (index == 2) {
      this.setData({
        "multiIndex[2]": value,

      })
     
    }
    var array=[],that =this;
    array[0]=  that.data.multiArray[0][that.data.multiIndex[0]];
    array[1]=that.data.multiArray[1][that.data.multiIndex[1]];
    array[2]=that.data.multiArray[2][that.data.multiIndex[2]];
    app.globalData.defaultCity=array[0]+','+array[1]+','+array[2]
  var that =this;
    that.setData({
        'nowList.current_page': 0,
    });
    that.getCurrentHospital()
   
  },
  getSiteData: function () {
    let that = this;
    var data = {};
    wx.showLoading({
      title: '加载中',
    })
    request.requestLoading(
        "/api/address/getArea",
        {},
        'POST',
      ).then((ret) => {
        var chinaData = ret.data;
        that.data.chinaData = chinaData;
        var sheng = []; //  设置省数组
        for (var i = 0; i < chinaData.length; i++) {
          sheng.push(chinaData[i].name);
        }
        that.setData({
          "multiArray[0]": sheng
        })
        that.getCity(); // 得到市
        wx.hideLoading({
            success: (res) => {},
          })
       
       
       
  
      }).catch((err) => {
        console.error(err);
      });
   
   
  },
  getCity: function () { //  得到市
    var shengNum = this.data.multiIndex[0];
    var chinaData = this.data.chinaData;
    console.log(shengNum)
    console.log(this.data.chinaData)
    var cityData = chinaData[shengNum].children;
    var city = [];
    for (var i = 0; i < cityData.length; i++) {
      city.push(cityData[i].name)
    }
    this.setData({
      "multiArray[1]": city
    })
   this.getXian()
  },
  getXian: function (e) { //  得到县
    var shengNum = this.data.multiIndex[0];
    var cityNum = this.data.multiIndex[1];
    var chinaData = this.data.chinaData;
 
    var c=[{id: 0, pid:  chinaData[shengNum].children[cityNum].id, name: "全部"}];
    var xianData = chinaData[shengNum].children[cityNum].children;
    xianData =c.concat(xianData)
    console.log(xianData)
    var xian = [];

    for (var i = 0; i < xianData.length; i++) {
      xian.push(xianData[i].name)
    }
    this.setData({
      "multiArray[2]": xian
    })
 
  },
  inputFirst(e) {
    this.setData({
      mima: e.detail.value
    })
  },
  foucusToggle(e){
    this.setData({
        foucusPop:!this.data.foucusPop
    })
  },
  calling(){
    wx.makePhoneCall({
        phoneNumber: this.data.contact_phone,
        success: function(res) {
          console.log('拨打电话成功！');
        },
        fail: function(res) {
          console.log('拨打电话失败！');
        }
      })
  },
  checkLogin(){
    if(this.data.userInfo){
        
        return true
    }else{
        wx.showModal({
          title: '提示',
          content: '您还未登录，去登录',
          complete: (res) => {
            if (res.cancel) {
                return false;
            }
        
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/login/index',
              })
            }
          }
        })
        return false;
    }
},
  setFirst() {
    this.setData({
      firstFocus: true
    })
  },
  jihuoPopToggle() {
    this.setData({
      jihuoPop: !this.data.jihuoPop,
      mima:''
    })
  },
  resultPopToggle() {
    this.setData({
      resultPop: !this.data.resultPop
    })
  },
  getBarInfo(e) {
    this.setData({
      topBarHeight: e.detail.topBarHeight
    })
  },
  activate(){
   if(this.checkLogin()){
       var mima='';
       this.setData({
           foucusPop:true,
           mima:''
       })
   }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("index options:", options)
   this.Check_Login(options);
   this.getSiteData();
   this.getCommon();
   console.log(wx.getStorageSync('userInfo'))

  
  },
  Check_Login(options){
        var that=this;
        wx.login({
            success: function (res) {
            if (res.code) {
                request.requestLoading(
                    "/api/login/checklogins",
                    {  
                      code: res.code,
                      from: options.from ? options.from : '',
                      data_id: options.id ? options.id : ''
                    },
                    'POST',
                  ).then((res) => {
                    if (res.code == 1) {
                        that.setData({
                            auth_type:res.data
                        })
                        wx.setStorageSync('openid', res.data.openid);
                        wx.setStorageSync('token', res.data.userinfo.token);
                        wx.setStorageSync('mobile', res.data.userinfo.mobile);
                        wx.setStorageSync('userInfo', res.data.userinfo)
                        
                        getApp().globalData.userInfo = res.data.userinfo;

                        that.setData({
                          userInfo: res.data.userinfo
                        })

                        wx.navigateBack({
                            delta:1
                        })
                       
                      } else {
                        functions.toast(res.msg)
                       
                      }
                  }).catch((err) => {
                    console.error(err);
                  });
              
              } else {
                console.log("用户失败")
              }
            }
          });
     
      },
  getnum()
  {
      var that =this;
    request.requestLoading(
        "/api/login/getMorders",
        {},
        'GET',
    ).then((res) => {
      // console.log(res);
      that.setData({
        appoints:res.data.appoints,
        rights:res.data.benefits
      })
     
    }).catch((err) => {
      // console.error(err);
      
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  gologoin(){
   wx.navigateTo({
     url: '/pages/login/index',
   })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      

    if(!wx.getStorageSync('token')){
    var that=this
    app.init_userInfo(true).then((res) => {
      
        wx.setStorageSync('userInfo', res)
        that.setData({
        userInfo: res
      })
      });
      if(!that.data.userInfo){
        setTimeout(function(){
            app.init_userInfo(true).then((res) => {
      
                wx.setStorageSync('userInfo', res)
                that.setData({
                userInfo: res
              })
              });

        },1000)
      }
 
  }else{
    app.init_userInfo(false).then((res) => {
        console.log(res)
        wx.setStorageSync('userInfo', res)
        this.setData({
        userInfo: res
      })
       });
      
  }
  console.log(wx.getStorageSync('userInfo'))

  this.getnum()
  this.getCitys()

  },
  checkPrivacy(){

  wx.getPrivacySetting({
      success: res => {
        console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
        if (res.needAuthorization) {
          // 需要弹出隐私协议
          this.setData({
            showPrivacy: true,
            privacyContractName:res.privacyContractName
          })
         
        
      
        } else {
           
       
        }
      },
      fail: () => {},
      complete: () => {}
    })

},
getCitys(){
    var that =this;
    /**
     *   lat:'',
    lng:'',
     //默认城市
     defaultCity:'',
     */
     console.log("go to getCItys：",app.globalData,that.data)
    if(app.globalData.lat==''){
        if(that.data.lng==''){
            app.getLocation(function (res) {
                // 经度
                console.log(res)
                var lng = res.longitude
                // 纬度
                var lat = res.latitude
                that.setData({
                  lng: lng,
                  lat: lat,
                  longitude:lng,
                  latitude:lat
                })
                that.getCurrentCitys()
               
              });
        }
    }else{
        that.setData({
            lng: app.globalData.lng,
            lat: app.globalData.lat,
            longitude:app.globalData.lng,
            latitude:app.globalData.lat
          })
          if(app.globalData.defaultCity==''){
            that.getCurrentCitys()
          }else{
              var citys= app.globalData.defaultCity.split(',');
            var chinaData = that.data.chinaData;
  
            var  index = that.data.multiArray[0].indexOf(citys[0]);
         
            if(index!=-1){
                that.setData({
                    'multiIndex[0]':index
                })
                var cityData = chinaData[index].children;
                var city = [];
                for (var i = 0; i < cityData.length; i++) {
                  city.push(cityData[i].name)
                }
                that.setData({
                  "multiArray[1]": city
                })
                var  index1 = that.data.multiArray[1].indexOf(citys[1]);
                if(index1!=-1){
                    console.log(index1)
                    that.setData({
                        'multiIndex[1]':index1,
                        isTrue:true
                    })    
                    var c=[{id: 0, pid:  chinaData[index].children[index1].id, name: "全部"}];
                    var xianData = chinaData[index].children[index1].children;
                    xianData=c.concat(xianData)
                    var xian = [];
                    for (var i = 0; i < xianData.length; i++) {
                      xian.push(xianData[i].name)
                    }
                    that.setData({
                      "multiArray[2]": xian
                    })
                    that.setData({
                        'multiIndex[2]':0
                    })
                    // var  index2 = that.data.multiArray[2].indexOf(citys[2]);
                    // if(index2!=-1){
                    //     that.setData({
                    //         'multiIndex[2]':index2
                    //     })
                       
                      
                   // }
                    that.getCurrentHospital()    
                }
            }
          }
        
    }
   

},
getCurrentCitys(){
    var that =this;
    request.requestLoading(
        "/api/distance/getCurrentCity",
        {
       lat:that.data.lat,
       lng:that.data.lng
        },
        'POST',
      ).then((ret) => {
       
       if(ret.code==1){
      
        var chinaData = that.data.chinaData;
  
        var  index = that.data.multiArray[0].indexOf(ret.data.province);
     
        if(index!=-1){
            that.setData({
                'multiIndex[0]':index
            })
            var cityData = chinaData[index].children;
            var city = [];
            for (var i = 0; i < cityData.length; i++) {
              city.push(cityData[i].name)
            }
            that.setData({
              "multiArray[1]": city
            })
            var  index1 = that.data.multiArray[1].indexOf(ret.data.city);
            if(index1!=-1){
                console.log(index1)
                that.setData({
                    'multiIndex[1]':index1,
                    isTrue:true
                })    
             
                var c=[{id: 0, pid:  chinaData[index].children[index1].id, name: "全部"}];
                var xianData = chinaData[index].children[index1].children;
                xianData=c.concat(xianData)
                var xian = [];
                for (var i = 0; i < xianData.length; i++) {
                  xian.push(xianData[i].name)
                }
                that.setData({
                  "multiArray[2]": xian
                })
                that.setData({
                    'multiIndex[2]':0
                })
                // var  index2 = that.data.multiArray[2].indexOf(ret.data.district);
                // if(index2!=-1){
                //     that.setData({
                //         'multiIndex[2]':index2
                //     })
                   
                  
                // }
                that.getCurrentHospital()    
            }
        }
       }
     
       
       
  
      }).catch((err) => {
        console.error(err);
      });
},
getCurrentHospital()
{
 
    var that =this;
    var json = {};
    json.nindex='';
    json.keywords='';
    json.page = Number(that.data.nowList.current_page) + 1;
    json.lat=that.data.lat;
    json.lng=that.data.lng;
    json.city=that.data.multiArray[1][that.data.multiIndex[1]];
    json.district=that.data.multiArray[2][that.data.multiIndex[2]];
    if (json.page > 1 && that.data.nowList.current_page >= that.data.nowList.last_page) {       
        return false;
    }
    request.requestLoading(
        "/api/distance/getHospitals",
        json,
        'POST',
      ).then((res) => {
       
        var nowList = res.data;
            that.setData({
                is_show:true
            })
    
            if (json.page > 1) {
                var now_nowList_data =that.data.nowList.data || [];
                var now_nowList_data = now_nowList_data.concat(nowList.data);
                nowList.data = now_nowList_data;
            }
      
            that.setData({
              nowList: nowList
            });
    
       
       
  
      }).catch((err) => {
        console.error(err);
      });
},
handleAgreePrivacyAuthorization() {
    this.setData({
        showPrivacy: false
      })
    this.getCitys()
 },
 togglePop3(){
    this.setData({
        showPrivacy: false
      })
 },
 handleOpenPrivacyContract() {
   // 打开隐私协议页面
   wx.openPrivacyContract({
     success: () => {}, // 打开成功
     fail: () => {}, // 打开失败
     complete: () => {}
   })
 },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getSiteData();
   this.getCommon();
   app.init_userInfo(true).then((res) => {
    if(res){
      wx.setStorageSync('userInfo', res)
      this.setData({
      userInfo: res
    })
    }
  });
  this.getnum()
  this.getCitys()
  setTimeout(function(){
    wx.stopPullDownRefresh();
  },500)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that =this;
    console.log(that.data.nowList.current_page)
    if (that.data.nowList.current_page >= that.data.nowList.last_page) {
      // functions.toast('已加载到底部了');
      return false;
  } else {
    that.getCurrentHospital()
  }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})